<!-- 友链编辑弹窗 -->
<template>
  <el-dialog :title="isUpdate ? '修改云挂机教程' : '添加云挂机教程'" :visible="visible" width="860px" :destroy-on-close="true"
    :lock-scroll="false" :close-on-click-modal="false" :before-close="confirmClose" @update:visible="updateVisible">
    <el-form ref="form" :model="form" :rules="rules" label-width="82px">
      <el-row :gutter="15">
        <el-col :sm="12">
          <el-form-item label="疑问:" prop="issue">
            <el-input clearable :maxlength="200" v-model="form.issue" placeholder="请输入挂机疑问" />
          </el-form-item>
        </el-col>
        <el-col :sm="12">
          <el-form-item label="排序:" prop="sort">
            <el-input clearable :maxlength="20" v-model="form.sort" placeholder="请输入排序" />
          </el-form-item>
        </el-col>
      </el-row>
      <!-- <el-form-item label="教程解答:" prop="answer" style="margin-top: 20px">
        <el-input :rows="6" clearable type="textarea"  v-model="form.answer" placeholder="请输入教程解答" />
      </el-form-item> -->
      <el-form-item label="教程解答:" prop="answer" style="margin-top: 20px">
        <tinymce-editor v-model="form.answer" :init="initEditor" />
      </el-form-item>
    </el-form>
    <div slot="footer">
            <el-button @click="confirmClose()">取消</el-button>
      <el-button type="primary" @click="save" :loading="loading">保存
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import TinymceEditor from '@/components/TinymceEditor'
export default {
  name: "YunCourseEdit",
  props: {
    // 弹窗是否打开
    visible: Boolean,
    // 修改回显的数据
    data: Object
  },
  components: { TinymceEditor },
  data() {
    return {
      // 表单数据
      form: Object.assign({}, this.data),
      // 表单验证规则
      rules: {
        issue: [{ required: true, message: "请输入疑问", trigger: "blur" }],
        sort: [{ required: true, message: "请输入排序", trigger: "blur" }],
        answer: [{ required: true, message: "请输入教程解答", trigger: "blur" }],
      },
      // 提交状态
      loading: false,
      // 是否是修改
      isUpdate: false,
    };
  },

  watch: {
    data() {
      if (this.data) {
        this.form = Object.assign({}, this.data);
        this.isUpdate = true;
      } else {
        this.form = {};
        this.isUpdate = false;
      }
    }
  },
  methods: {
    /* 保存编辑 */
    save() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.loading = true;
          this.$http
            .post("/BoxYunCourse/edit", this.form)
            .then(res => {
              this.loading = false;
              if (res.data.code === 0) {
                this.$message.success(res.data.msg);
                if (!this.isUpdate) {
                  this.form = {};
                }
                this.updateVisible(false);
                this.$emit("done");
              } else {
                this.$message.error(res.data.msg);
              }
            })
            .catch(e => {
              this.loading = false;
              this.$message.error(e.message);
            });
        } else {
          return false;
        }
      });
    },
    /* 更新visible */
    updateVisible(value) {
      this.$emit("update:visible", value);
    },

    confirmClose() {
      this.$confirm("确定要返回吗？", "温馨提示")
        .then(() => {
          this.updateVisible(false);
          if (!this.isUpdate) {
            this.form = {};
          }
        })
        .catch(() => { });
    },

    
    //判断上传的文件类型
    judgmentType(fileValue) {
      var result = {}
      var index = fileValue.indexOf('.') //（考虑严谨用lastIndexOf(".")得到）得到"."在第几位
      var fileValueSuffix = fileValue.substring(index) //截断"."之前的，得到后缀
      if (/(.*)\.(mp4|rmvb|avi|ts)$/.test(fileValueSuffix)) {
        //根据后缀，判断是否符合视频格式
        result.url = fileValue
        result.type = 2
        result.cover = fileValue + '?x-oss-process=video/snapshot,t_1000,m_fast'
        // this.getVideoBase64(
        //   fileValue
        // ).then(res => {
        //   result.cover = res;
        // });
      }

      if (/(.*)\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(fileValueSuffix)) {
        //根据后缀，判断是否符合图片格式
        result.url = fileValue
        result.type = 1
        result.cover = fileValue
      }

      return result
    },

    //校验视频格式和内存大小
    validateVideo(file) {
      const isMP4 = file.type === 'video/mp4'
      // const isLt3M = file.size / 1024 / 1024 < 5;

      if (!isMP4) {
        this.$message.error('上传视频必须为 MP4 格式！')

        return false
      }

      // if (!isLt3M) {
      //   this.$message.error("上传视频大小限制 5M 以内！");

      //   return false;
      // }

      // const duration = this.getVideoDuration(file);
      // if (duration > 60) {
      //   this.$message.error("上传视频时长不能超过 60 秒！");

      //   return false;
      // }

      return true
    },
    //获取视频源
    getVideoDuration(file) {
      return new Promise((resolve) => {
        const videoElement = document.createElement('video')
        videoElement.src = URL.createObjectURL(file)

        videoElement.addEventListener('loadedmetadata', () => {
          resolve(videoElement.duration)
        })
      })
    },
    //上传视频
    uploadFile(file, folder = 'images') {
      console.log(folder)
      const formData = new FormData()
      formData.append('file', file)
      this.$http.post('/upload/uploadImageOss', formData).then((res) => {
        // console.log(res.data.data, " res.data.data");
        // console.log(res,'res')
        if (res.data.code == 0) {
          this.videomsg.url = res.data.data
          this.videomsg.name = file.name

          // return {
          //   url: res.data,
          //   name: file.name,
          // };
        } else {
          this.$message({
            message: res.message,
            type: 'error',
            duration: '5000'
          })
        }
      })
    },
  }
};
</script>

<style scoped></style>
